package modbus_client

import (
	"container/list"
	"sync"
)

// MessageQueue 消息队列结构体
type MessageQueue struct {
	queue   *list.List
	maxSize int
	mu      sync.Mutex
}

// NewMessageQueue 创建新的消息队列实例
func NewMessageQueue(maxSize int) *MessageQueue {
	return &MessageQueue{
		queue:   list.New(),
		maxSize: maxSize,
	}
}

// Enqueue 添加消息到队列尾部
func (mq *MessageQueue) Enqueue(message interface{}) {
	mq.mu.Lock()
	defer mq.mu.Unlock()

	if mq.queue.Len() >= mq.maxSize {
		mq.queue.Remove(mq.queue.Front())
	}
	mq.queue.PushBack(message)
}

// Dequeue 从队列头部取出消息
func (mq *MessageQueue) Dequeue() interface{} {
	mq.mu.Lock()
	defer mq.mu.Unlock()

	if mq.queue.Len() == 0 {
		return nil
	}
	element := mq.queue.Front()
	mq.queue.Remove(element)
	return element.Value
}

// Size 获取当前队列大小
func (mq *MessageQueue) Size() int {
	mq.mu.Lock()
	defer mq.mu.Unlock()
	return mq.queue.Len()
}

// IsEmpty 检查队列是否为空
func (mq *MessageQueue) IsEmpty() bool {
	mq.mu.Lock()
	defer mq.mu.Unlock()
	return mq.queue.Len() == 0
}

// IsFull 检查队列是否已满
func (mq *MessageQueue) IsFull() bool {
	mq.mu.Lock()
	defer mq.mu.Unlock()
	return mq.queue.Len() >= mq.maxSize
}

// Clear 清空队列
func (mq *MessageQueue) Clear() {
	mq.mu.Lock()
	defer mq.mu.Unlock()
	mq.queue.Init()
}

// GetAll 获取队列中所有消息的切片
func (mq *MessageQueue) GetAll() []interface{} {
	mq.mu.Lock()
	defer mq.mu.Unlock()

	var messages []interface{}
	for element := mq.queue.Front(); element != nil; element = element.Next() {
		messages = append(messages, element.Value)
	}
	return messages
}
